package util.aes;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;

/**
 * aes 加解密算法
 *
 * @author tianbl
 * @since 2020/07/07
 **/
public class AESUtil {

    /**
     * 密钥算法
     */
    private static final String ALGORITHM = "AES";

    /**
     * 加解密算法/工作模式/填充方式
     */
    private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS7Padding";

    /**
     * AES加密
     *
     * @param key  秘钥
     * @param data d
     * @return str
     * @throws Exception e
     */
    public static String encryptData(SecretKeySpec key, String data) throws Exception {
        // 创建密码器
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING, "BC");
        // 初始化
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return base64Encode8859(new String(cipher.doFinal(data.getBytes()), StandardCharsets.ISO_8859_1));

    }

    /**
     * AES解密
     *
     * @param base64Data 64
     * @return str
     * @throws Exception e
     */
    public static String decryptData(SecretKeySpec key, String base64Data) throws Exception {
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING, "BC");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return new String(cipher.doFinal(base64Decode8859(base64Data).getBytes(StandardCharsets.ISO_8859_1)), StandardCharsets.UTF_8);
    }

    /**
     * Base64解码
     *
     * @param source base64 str
     * @return str
     */
    public static String base64Decode8859(final String source) {
        final Base64.Decoder decoder = Base64.getDecoder();
        // 此处的字符集是ISO-8859-1
        return new String(decoder.decode(source), StandardCharsets.ISO_8859_1);
    }

    /**
     * Base64加密
     *
     * @param source str
     * @return base64 str
     */
    public static String base64Encode8859(final String source) {
        final Base64.Encoder encoder = Base64.getEncoder();
        byte[] textByte;
        //注意此处的编码是ISO-8859-1
        textByte = source.getBytes(StandardCharsets.ISO_8859_1);
        return encoder.encodeToString(textByte);
    }
}
